from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.clickjacking import xframe_options_sameorigin
from web import models
from web.forms.wiki import WikiModelForm
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from utils.tencent.cos import upload_file
from utils.encrypt import uid


def wiki(request,project_id):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_obj = models.Wiki.objects.filter(id=wiki_id,project_id=project_id).first()

    return render(request,'wiki.html',{'wiki_obj':wiki_obj})


def wiki_add(request,project_id):
    if request.method == "GET":
        form = WikiModelForm(request)
        return render(request,'wiki_form.html',{'form':form})

    form =  WikiModelForm(request,data=request.POST)
    if form.is_valid():
        # 添加目录层级
        if form.instance.parent:
            form.instance.parent.depth += 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project

        form.save()
        url = reverse('wiki',kwargs={'project_id':project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})

def wiki_del(request,project_id,wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(id=wiki_id,project_id=project_id).delete()
    return redirect(reverse('wiki',kwargs={'project_id':project_id}))

def wiki_edit(request,project_id,wiki_id):
    """编辑文章"""
    wiki_obj = models.Wiki.objects.filter(id=wiki_id,project_id=project_id).first()
    if not wiki_obj:
        return redirect(reverse('wiki', kwargs={'project_id': project_id}))
    if request.method == "GET":
        form = WikiModelForm(request,instance=wiki_obj)
        return render(request,'wiki_form.html',{'form':form})
    form = WikiModelForm(request,data=request.POST,instance=wiki_obj)
    if form.is_valid():
        # 添加目录层级
        if form.instance.parent:
            form.instance.parent.depth += 1
        else:
            form.instance.depth = 1

        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki_id={1}".format(url,wiki_id)
        return redirect(preview_url)
    return render(request, 'wiki_form.html', {'form': form})

def wiki_catalog(request,project_id):
    """wiki目录"""
    # data = models.Wiki.objects.filter(project=request.tracer.project).values_list('id','title')
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id','title','parent_id').order_by('depth','id')
    return JsonResponse({'status':True,'data':list(data)})

@xframe_options_sameorigin
@csrf_exempt
def wiki_upload(request,project_id):
    """markdown上传图片"""
    result = {
        'success': 0,
        'message': None,
        'url': None,
    }
    # print(request.FILES)
    # <MultiValueDict: {'editormd-image-file': [<InMemoryUploadedFile: star.jpeg (image/jpeg)>]}>
    image_obj = request.FILES.get('editormd-image-file')
    if not image_obj:
        result['message'] = "文件不存在"
        return JsonResponse(result)
    ext = image_obj.name.rsplit('.')[-1] # 得到文件的后缀名
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone),ext)
    image_url = upload_file(
        bucket=request.tracer.project.bucket,
        file_obj=image_obj,
        key=key,
        region=request.tracer.project.region,
    )
    # 向markdown返回结果
    result['success'] = 1
    result['url'] = image_url
    # print(image_url)
    # print(result)
    return JsonResponse(result)

